package com.arpa.wms.common.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.LogUtil;
import com.arpa.ntocc.common.domain.entity.PartyGroupConfig;
import com.arpa.ntocc.common.service.IPartyGroupConfigService;
import com.arpa.wms.common.ess.ElectronicFaceSheetBlanaceDTO;
import com.arpa.wms.common.ess.ElectronicFaceSheetDTO;
import com.arpa.wms.domain.consts.MiddlegroundOutBound;
import com.arpa.wms.domain.consts.ResultDO;
import com.arpa.wms.domain.dto.FaceBillBalanceDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 阿帕云访问工具类
 * @Author liuyj
 * @Date 2020-02-13 09:32:29
 */
@Component
@Log4j2(topic = "business")
public class ArpaCloudUtil {

    /**
     * 机构阿帕云服务配置信息
     * key: branchCode , value: 每个机构的阿帕云服务配置
     */
    private static Map<String,CustomerAPPInfo> branchConfigMap=new HashMap<>();

    @Autowired
    IPartyGroupConfigService partyGroupConfigService;

    /**
     * 初始化短信接口配置
     */
    @PostConstruct
    public void initConfig() {
        try {
            branchConfigMap.clear();
            List<PartyGroupConfig> configList = partyGroupConfigService.list(new QueryWrapper<PartyGroupConfig>().lambda().eq(PartyGroupConfig::getType,"arpaCloud"));
            if(CollectionUtils.isEmpty(configList)){
                log.error(LogUtil.log("++阿帕云配置缺失，请检查配置。++"));
            }
            for(PartyGroupConfig config:configList){
                String branchCode = config.getBranchCode();
                CustomerAPPInfo customerAPPInfo = Optional.ofNullable(branchConfigMap.get(branchCode)).orElse(new CustomerAPPInfo());
                String value = config.getConfigValue();
                switch (config.getConfigKey()){
                    //基本用户配置信息
                    case "arpaCloudTokenApiUrl": customerAPPInfo.setArpaCloudTokenApiUrl(value); break;
                    case "customerCode": customerAPPInfo.setCustomerCode(value); break;
                    case "appName": customerAPPInfo.setAppName(value); break;
                    case "appSecret": customerAPPInfo.setAppSecret(value); break;
                    case "expireSecendInterval": customerAPPInfo.setExpireSecendInterval(Long.valueOf(value)); break;






                    //仓储按单扣费
                    case "orderDetailChargeUrl": customerAPPInfo.setOrderDetailChargeUrl(value); break;
                    //账户余额
                    case "customerAccount": customerAPPInfo.setCustomerAccount(value); break;

                    //充值记录
                    case "customerChargetList":customerAPPInfo.setCustomerChargetList(value);break;
                    //客户账户信息
                    case "warehousingAccount":customerAPPInfo.setWarehousingAccount(value);break;
                    //是否是充值用户
                    case "rechargeUser":customerAPPInfo.setRechargeUser(value);break;
                    //是否是充值用户
                    case "loadState":customerAPPInfo.setLoadState(value);break;
                    case "templateList":customerAPPInfo.setTemplateList(value);break;
                    case "electronicFaceSheet":customerAPPInfo.setElectronicFaceSheet(value);break;
                    case "electronicFaceSheetBalance":customerAPPInfo.setElectronicFaceSheetBalance(value);break;
                    case "cancelElectronicFaceSheet":customerAPPInfo.setCancelElectronicFaceSheet(value);break;

                    default:
                }
                branchConfigMap.put(branchCode,customerAPPInfo);
            }
            log.info("++阿帕云配置初始化完成。++");
        } catch (Exception e) {
            log.error("catch Exception",e);
        }
    }




    /**
     * 获取阿帕云访问token
     * @param app 0 默认app，1 货主jpushAPP，2 司机jpushAPP
     * @return
     */
    public static String getToken(String branchCode,int app) throws Exception {
        CustomerAPPInfo ca = branchConfigMap.get(branchCode);
        Map<String,Object> params = new HashMap<>();
        params.put("customerCode",ca.getCustomerCode());
        switch (app){
            case 0:
                params.put("name",ca.getAppName());
                params.put("secret",ca.getAppSecret());
                break;
            default: throw new Exception("不支持的app序号");
        }
        //加签名
        params = getSignature(params,ca.getArpaCloudsignSecret());
        //请求接口获取token
        String reslut = HttpRequest.post(ca.getArpaCloudTokenApiUrl()).form(params).execute().body();
        log.info("arpaCloud返回reslut:"+reslut);
        ResultDO resultDO = JSONUtil.toBean(reslut, ResultDO.class);
        if(resultDO != null && resultDO.getStatus() == 0){
            long expireSecendInterval = ca.getExpireSecendInterval();
            switch (app){
                case 0:
                    String token = resultDO.getData().toString();
                    ca.setToken(token);
                    ca.setExpireTime(LocalDateTime.now().plusSeconds(expireSecendInterval));
                    return token;
                case 1:
                    String token_jpush_shipment = resultDO.getData().toString();
                    ca.setToken_jpush_shipment(token_jpush_shipment);
                    ca.setExpireTime_jpush_shipment(LocalDateTime.now().plusSeconds(expireSecendInterval));
                    return token_jpush_shipment;
                case 2:
                    String token_jpush_driver = resultDO.getData().toString();
                    ca.setToken_jpush_driver(token_jpush_driver);
                    ca.setExpireTime_jpush_dirver(LocalDateTime.now().plusSeconds(expireSecendInterval));
                    return token_jpush_driver;
                default: throw new Exception("不支持的app序号");
            }
        }else{
            log.error(LogUtil.log("获取阿帕云token异常"));
            return null;
        }
    }


    /**
     * 上报出库运单并扣费接口
     * @param
     * @param branchCode
     * @return
     */
    public ResultDO jinchangOrderDetailCharge(MiddlegroundOutBound orderDetailDTO, String branchCode){
        ResultDO resultDO = new ResultDO();
        try {
            CustomerAPPInfo ca =branchConfigMap.get(branchCode);
            if(ca==null){
                initConfig();
                ca =branchConfigMap.get(branchCode);
                if(ca==null) {
                    resultDO.setMsg("失败:该机构缺少阿帕云服务配置！");
                    resultDO.setStatus(-1);
                    return resultDO;
                }
            }

            //查询是否是充值用户
            PartyGroupConfig config = partyGroupConfigService.getOne(new QueryWrapper<PartyGroupConfig>().lambda().eq(PartyGroupConfig::getType,"arpaCloud")
                    .eq(PartyGroupConfig::getBranchCode,branchCode).eq(PartyGroupConfig::getConfigKey,"rechargeUser"));
            if(config.getConfigValue().equalsIgnoreCase("no")){  //不是充值用户
                resultDO.setMsg("不是充值用户无需扣费");
                resultDO.setStatus(0);
                return resultDO;
            }

            String token = ca.getToken();
            String orderDetailChargeUrl = ca.getOrderDetailChargeUrl();
            LocalDateTime expireTime = ca.getExpireTime();
            //加签名
            Map<String,Object> params = BeanUtil.beanToMap(orderDetailDTO);
            params = getSignature(params,ca.getArpaCloudsignSecret());
            //无token或者过了失效时间重新获取token
            if(token == null || expireTime == null || expireTime.isBefore(LocalDateTime.now())){
                getToken(branchCode,0);
            }
            //获取最新token
            token = ca.getToken();
            String jsonStr = JSONUtil.toJsonStr(params);
            String reslut = HttpRequest.post(orderDetailChargeUrl)
                    .header("authorization",token)
                    .header("Content-Type","application/json")
                    .body(jsonStr).execute().body();
            log.info(LogUtil.log("扣费结果："+reslut + "出库单号" + orderDetailDTO.getOutboundCode()));
            resultDO = JSONUtil.toBean(reslut, ResultDO.class);
            return  resultDO;
        } catch (Exception e) {
            resultDO.setMsg("扣费失败:"+e.getMessage());
            resultDO.setStatus(-1);
            return resultDO;
        }
    }

    /**
     * 获取云打印标准模板列表
     * @param type 平台类型：1菜鸟，2京东，3拼多多
     * @param cpCode 物流code
     * @param dynamicToken 用户token
     * @param branchCode 机构标识
     * @return
     */
    public ResultDO getCloudprintStandardTemplates(int type,String cpCode,String dynamicToken, String branchCode){
        ResultDO resultDO = new ResultDO();
        try {
            CustomerAPPInfo ca =branchConfigMap.get(branchCode);
            if(ca==null){
                initConfig();
                ca =branchConfigMap.get(branchCode);
                if(ca==null) {
                    resultDO.setMsg("失败:该机构缺少阿帕云服务配置！");
                    resultDO.setStatus(-1);
                    return resultDO;
                }
            }


            String token = ca.getToken();
            String templateList = ca.getTemplateList();
            LocalDateTime expireTime = ca.getExpireTime();
            //加签名
            Map<String,Object> params = new HashMap<>();
            params.put("type",type);
            params.put("cpCode",cpCode);
            params.put("dynamicToken",dynamicToken);
            params = getSignature(params,ca.getArpaCloudsignSecret());
            //无token或者过了失效时间重新获取token
            if(token == null || expireTime == null || expireTime.isBefore(LocalDateTime.now())){
                getToken(branchCode,0);
            }
            //获取最新token
            token = ca.getToken();
            String reslut = HttpRequest.get(templateList)
                    .header("authorization",token)
                    .header("Content-Type","application/json")
                    .form(params) .execute().body();
            resultDO = JSONUtil.toBean(reslut, ResultDO.class);
            return  resultDO;
        } catch (Exception e) {
            resultDO.setMsg("获取电子面单模板失败:"+e.getMessage());
            resultDO.setStatus(-1);
            return resultDO;
        }
    }

    /**
     * 获取电子面单打印数据
     * @param dto 获取参数
     * @param branchCode 机构标识
     * @return
     */
    public ResultDO getWaybillPrintData(ElectronicFaceSheetDTO dto, String branchCode){
        log.info("中台获取面单号请求参数：{}",JSONUtil.toJsonStr(dto));
        ResultDO resultDO = new ResultDO();
        try {
            CustomerAPPInfo ca =branchConfigMap.get(branchCode);
            if(ca==null){
                initConfig();
                ca =branchConfigMap.get(branchCode);
                if(ca==null) {
                    resultDO.setMsg("失败:该机构缺少阿帕云服务配置！");
                    resultDO.setStatus(-1);
                    return resultDO;
                }
            }


            String token = ca.getToken();
            String electronicFaceSheet = ca.getElectronicFaceSheet();
            LocalDateTime expireTime = ca.getExpireTime();
            //加签名
            Map<String,Object> params = BeanUtil.beanToMap(dto);
            //params = getSignature(params,ca.getArpaCloudsignSecret());
            //无token或者过了失效时间重新获取token
            if(token == null || expireTime == null || expireTime.isBefore(LocalDateTime.now())){
                getToken(branchCode,0);
            }
            //获取最新token
            token = ca.getToken();
            String jsonStr = JSONUtil.toJsonStr(params);
            String reslut = HttpRequest.post(electronicFaceSheet)
                    .header("authorization",token)
                    .header("Content-Type","application/json")
                    .body(jsonStr) .execute().body();
            resultDO = JSONUtil.toBean(reslut, ResultDO.class);
            log.info("中台电子面单返回数据:{}",resultDO);
            return  resultDO;
        } catch (Exception e) {
            resultDO.setMsg("获取电子面单模板失败:"+e.getMessage());
            resultDO.setStatus(-1);
            return resultDO;
        }
    }


    /**
     * 获取电子面单账户余额
     * @param dto 获取参数
     * @param branchCode 机构标识
     * @return
     */
    public ResultDO getWaybillPrintDataBalance(ElectronicFaceSheetBlanaceDTO dto, String branchCode){
        log.info("中台获取面单余额请求参数：{}",JSONUtil.toJsonStr(dto));
        ResultDO resultDO = new ResultDO();
        try {
            CustomerAPPInfo ca =branchConfigMap.get(branchCode);
            if(ca==null){
                initConfig();
                ca =branchConfigMap.get(branchCode);
                if(ca==null) {
                    resultDO.setMsg("失败:该机构缺少阿帕云服务配置！");
                    resultDO.setStatus(-1);
                    return resultDO;
                }
            }


            String token = ca.getToken();
            String electronicFaceSheetBalance = ca.getElectronicFaceSheetBalance();
            LocalDateTime expireTime = ca.getExpireTime();
            //加签名
            Map<String,Object> params = BeanUtil.beanToMap(dto);
//            params = getSignature(params,ca.getArpaCloudsignSecret());
            //无token或者过了失效时间重新获取token
            if(token == null || expireTime == null || expireTime.isBefore(LocalDateTime.now())){
                getToken(branchCode,0);
            }
            //获取最新token
            token = ca.getToken();
            String jsonStr = JSONUtil.toJsonStr(params);
            String reslut = HttpRequest.post(electronicFaceSheetBalance)
                    .header("authorization",token)
                    .header("Content-Type","application/json")
                    .body(jsonStr) .execute().body();
            resultDO = JSONUtil.toBean(reslut, ResultDO.class);
            log.info("中台电子面单余额返回数据:{}",resultDO);
            return  resultDO;
        } catch (Exception e) {
            resultDO.setMsg("获取电子面单余额失败:"+e.getMessage());
            resultDO.setStatus(-1);
            return resultDO;
        }
    }


    /**
     * 取消电子面单
     * @param dto 获取参数
     * @param branchCode 机构标识
     * @return
     */
    public ResultDO cancelwaybillPrintData(ElectronicFaceSheetBlanaceDTO dto, String branchCode){
        log.info("中台获取面单余额请求参数：{}",JSONUtil.toJsonStr(dto));
        ResultDO resultDO = new ResultDO();
        try {
            CustomerAPPInfo ca =branchConfigMap.get(branchCode);
            if(ca==null){
                initConfig();
                ca =branchConfigMap.get(branchCode);
                if(ca==null) {
                    resultDO.setMsg("失败:该机构缺少阿帕云服务配置！");
                    resultDO.setStatus(-1);
                    return resultDO;
                }
            }


            String token = ca.getToken();
            String electronicFaceSheetBalance = ca.getCancelElectronicFaceSheet();
            LocalDateTime expireTime = ca.getExpireTime();
            //加签名
            Map<String,Object> params = BeanUtil.beanToMap(dto);
//            params = getSignature(params,ca.getArpaCloudsignSecret());
            //无token或者过了失效时间重新获取token
            if(token == null || expireTime == null || expireTime.isBefore(LocalDateTime.now())){
                getToken(branchCode,0);
            }
            //获取最新token
            token = ca.getToken();
            String jsonStr = JSONUtil.toJsonStr(params);
            String reslut = HttpRequest.post(electronicFaceSheetBalance)
                    .header("authorization",token)
                    .header("Content-Type","application/json")
                    .body(jsonStr) .execute().body();
            resultDO = JSONUtil.toBean(reslut, ResultDO.class);
            log.info("中台取消电子面单返回数据:{}",resultDO);
            return  resultDO;
        } catch (Exception e) {
            resultDO.setMsg("获取取消电子面单失败:"+e.getMessage());
            resultDO.setStatus(-1);
            return resultDO;
        }
    }

//    private void init2() {
//        try {
//            branchConfigMap.clear();
//            List<PartyGroupConfig> configList = partyGroupConfigService.list(new QueryWrapper<PartyGroupConfig>().lambda().eq(PartyGroupConfig::getType,"arpaCloud"));
//            if(CollectionUtils.isEmpty(configList)){
//                log.error(LogUtil.log("++阿帕云配置缺失，请检查配置。++"));
//            }
//            for(PartyGroupConfig config:configList){
//                String branchCode = config.getBranchCode();
//                CustomerAPPInfo customerAPPInfo = Optional.ofNullable(branchConfigMap.get(branchCode)).orElse(new CustomerAPPInfo());
//                String value = config.getConfigValue();
//                switch (config.getConfigKey()){
//                    //基本用户配置信息
//                    case "arpaCloudTokenApiUrl": customerAPPInfo.setArpaCloudTokenApiUrl(value); break;
//                    case "customerCode": customerAPPInfo.setCustomerCode(value); break;
//                    case "appName": customerAPPInfo.setAppName(value); break;
//                    case "appSecret": customerAPPInfo.setAppSecret(value); break;
//                    case "expireSecendInterval": customerAPPInfo.setExpireSecendInterval(Long.valueOf(value)); break;
//
//
//
//
//
//
//                    //仓储按单扣费
//                    case "orderDetailChargeUrl": customerAPPInfo.setOrderDetailChargeUrl(value); break;
//
//                    //充值记录
//                    case "customerChargetList":customerAPPInfo.setCustomerChargetList(value);break;
//                    //客户账户信息
//                    case "warehousingAccount":customerAPPInfo.setWarehousingAccount(value);break;
//                    //是否是充值用户
//                    case "rechargeUser":customerAPPInfo.setRechargeUser(value);break;
//                    //是否是充值用户
//                    case "loadState":customerAPPInfo.setLoadState(value);break;
//
//                    default:
//                }
//                branchConfigMap.put(branchCode,customerAPPInfo);
//            }
//            log.info("++阿帕云配置初始化完成。++");
//        } catch (Exception e) {
//            log.error("catch Exception",e);
//        }
//    }

    /**
     * 查询客户账户信息
     * @param branchCode
     * @return
     */
    public ResultDO changAccount(String branchCode){
        ResultDO resultDO = new ResultDO();
        try {
            CustomerAPPInfo ca =branchConfigMap.get(branchCode);
            if(ca==null){
                initConfig();
                ca =branchConfigMap.get(branchCode);
                if(ca==null) {
                    resultDO.setMsg("失败:该机构缺少阿帕云服务配置！");
                    resultDO.setStatus(-1);
                    return resultDO;
                }
            }

            //查询是否是充值用户
            PartyGroupConfig config = partyGroupConfigService.getOne(new QueryWrapper<PartyGroupConfig>().lambda().eq(PartyGroupConfig::getType,"arpaCloud")
                    .eq(PartyGroupConfig::getBranchCode,branchCode).eq(PartyGroupConfig::getConfigKey,"rechargeUser"));
            if(config.getConfigValue().equalsIgnoreCase("no")){  //不是充值用户
                resultDO.setMsg("不是充值用户无需扣费");
                resultDO.setStatus(0);
                return resultDO;
            }


            String token = ca.getToken();
            String warehousingAccount = ca.getWarehousingAccount();
            LocalDateTime expireTime = ca.getExpireTime();
            //加签名
            Map<String,Object> params = new HashMap<>();
            params = getSignature(params,ca.getArpaCloudsignSecret());
            //无token或者过了失效时间重新获取token
            if(token == null || expireTime == null || expireTime.isBefore(LocalDateTime.now())){
                getToken(branchCode,0);
            }
            //获取最新token
            token = ca.getToken();
            String reslut = HttpRequest.get(warehousingAccount)
                    .header("authorization",token)
                    .header("Content-Type","application/x-www-form-urlencoded")
                    .form(params)
                    .execute().body();
            log.info(LogUtil.log("查询结果："+reslut));
            resultDO = JSONUtil.toBean(reslut, ResultDO.class);
            return  resultDO;
        } catch (Exception e) {
            resultDO.setMsg("查询失败:"+e.getMessage());
            resultDO.setStatus(-1);
            return resultDO;
        }
    }


    /**
     * 查询客户账户信息
     * @param branchCode
     * @return
     */
    public ResultDO changAccountList(String branchCode){
        ResultDO resultDO = new ResultDO();
        try {
            CustomerAPPInfo ca =branchConfigMap.get(branchCode);
            if(ca==null){
                initConfig();
                ca =branchConfigMap.get(branchCode);
                if(ca==null) {
                    resultDO.setMsg("失败:该机构缺少阿帕云服务配置！");
                    resultDO.setStatus(-1);
                    return resultDO;
                }
            }
            String token = ca.getToken();
            String warehousingAccount = ca.getWarehousingAccount();
            LocalDateTime expireTime = ca.getExpireTime();
            //加签名
            Map<String,Object> params = new HashMap<>();
            params = getSignature(params,ca.getArpaCloudsignSecret());
            //无token或者过了失效时间重新获取token
            if(token == null || expireTime == null || expireTime.isBefore(LocalDateTime.now())){
                getToken(branchCode,0);
            }
            //获取最新token
            token = ca.getToken();
            String reslut = HttpRequest.get(warehousingAccount)
                    .header("authorization",token)
                    .header("Content-Type","application/x-www-form-urlencoded")
                    .form(params)
                    .execute().body();
            log.info(LogUtil.log("查询结果："+reslut));
            resultDO = JSONUtil.toBean(reslut, ResultDO.class);
            return  resultDO;
        } catch (Exception e) {
            resultDO.setMsg("查询失败:"+e.getMessage());
            resultDO.setStatus(-1);
            return resultDO;
        }
    }


    /**
     * 查询客户账户余额
     * @param branchCode
     * @return
     */
    public ResultDO customerAccount(String branchCode){
        ResultDO resultDO = new ResultDO();
        try {
            CustomerAPPInfo ca =branchConfigMap.get(branchCode);
            if(ca==null){
                initConfig();
                ca =branchConfigMap.get(branchCode);
                if(ca==null) {
                    resultDO.setMsg("失败:该机构缺少阿帕云服务配置！");
                    resultDO.setStatus(-1);
                    return resultDO;
                }
            }

            //查询是否是充值用户
            PartyGroupConfig config = partyGroupConfigService.getOne(new QueryWrapper<PartyGroupConfig>().lambda().eq(PartyGroupConfig::getType,"arpaCloud")
                    .eq(PartyGroupConfig::getBranchCode,branchCode).eq(PartyGroupConfig::getConfigKey,"rechargeUser"));
            if(config.getConfigValue().equalsIgnoreCase("no")){  //不是充值用户
                resultDO.setMsg("不是充值用户无需扣费");
                resultDO.setStatus(0);
                return resultDO;
            }


            String token = ca.getToken();
            String customerAccount = ca.getCustomerAccount();
            LocalDateTime expireTime = ca.getExpireTime();
            //加签名
            Map<String,Object> params = new HashMap<>();
            params.put("type","ORDERCHARGE");
            params = getSignature(params,ca.getArpaCloudsignSecret());
            //无token或者过了失效时间重新获取token
            if(token == null || expireTime == null || expireTime.isBefore(LocalDateTime.now())){
                getToken(branchCode,0);
            }
            //获取最新token
            token = ca.getToken();
            String reslut = HttpRequest.get(customerAccount)
                    .header("authorization",token)
                    .header("Content-Type","application/x-www-form-urlencoded")
                    .form(params)
                    .execute().body();
            log.info(LogUtil.log("查询结果："+reslut));
            resultDO = JSONUtil.toBean(reslut, ResultDO.class);
            return  resultDO;
        } catch (Exception e) {
            resultDO.setMsg("查询失败:"+e.getMessage());
            resultDO.setStatus(-1);
            return resultDO;
        }
    }





    /**
     * 客户充值记录
     * @return
     */
    public ResultDO customerCharget(String type, String gmtCreatedStart, String gmtCreatedEnd, String pageNum, String pageSize, String sortField, String branchCode){
        try {
            if("freeOrder".equals(sortField)){
                sortField = "isFreeOrder";
            }
            CustomerAPPInfo ca =branchConfigMap.get(branchCode);
            if(ca==null){
                initConfig();
                ca =branchConfigMap.get(branchCode);
                if(ca==null) {
                    log.error("失败:该机构缺少阿帕云服务配置！");
                    throw new ServiceException("该机构缺少阿帕云服务配置");
                }
            }
            //重新加载配置
//            if(!StringUtils.isEmpty(ca.loadState)){
//                PartyGroupConfig config = partyGroupConfigService.getOne(new QueryWrapper<PartyGroupConfig>().lambda().eq(PartyGroupConfig::getType,"arpaCloud")
//                .eq(PartyGroupConfig::getBranchCode,branchCode).eq(PartyGroupConfig::getConfigKey,"loadState"));
//                if(!StringUtils.isEmpty(config) && config.getConfigValue().equalsIgnoreCase("yes")){
//                    initConfig();
//                    ca =branchConfigMap.get(branchCode);
//                }
//            }

            String token = ca.getToken();
            String customerChargetList = ca.getCustomerChargetList();
            LocalDateTime expireTime = ca.getExpireTime();

            Map<String,Object> params = new HashMap<>();
            params.put("type",type);
//            params.put("freeOrder",freeOrder);
            params.put("gmtCreatedStart",gmtCreatedStart);
            params.put("gmtCreatedEnd",gmtCreatedEnd);
//            params.put("description",description);
            params.put("pageNum",pageNum);
            params.put("pageSize",pageSize);
            params.put("sortField",sortField);
            params.put("sortType","desc");
            //加签名
            params = getSignature(params,ca.getArpaCloudsignSecret());
            //无token或者过了失效时间重新获取token
            if(token == null || expireTime == null || expireTime.isBefore(LocalDateTime.now())){
                getToken(branchCode,0);
            }
            //获取最新token
            token = ca.getToken();
            String reslut = HttpRequest.get(customerChargetList).header("authorization",token).form(params).execute().body();
            log.info(LogUtil.log("查询平台充值结果："+reslut));
            ResultDO resultDO = JSONUtil.toBean(reslut, ResultDO.class);
            return resultDO;
        } catch (Exception e) {
            log.error("查询平台充值失败:"+e.getMessage());
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 签名
     * @param params
     * @param signSecret
     */
    private static Map<String,Object> getSignature(Map<String,Object> params,String signSecret) {
        //添加验签参数
        //客户分配的验签秘钥
        //String signSecret = "";
        params.put("SIGN_TYPE", "SHA256");
        params.put("SIGN_TIMESTAMP", DateUtil.format(new Date(),"yyyyMMddHHmmss"));
        params.put("SIGN_NONCE", RandomUtil.randomString(8));
        String sign = SignatureUtils.getSign(params, signSecret);
        System.out.println("秘钥值："+signSecret);
        System.out.println("签名值："+sign);
        params.put("SIGN_VALUE", sign);
        return params;
    }


    /**
     * 通过反射方式根据对象属性名称获取属性值
     * @param fieldName
     * @param info
     * @return
     */
    private static String getPlatUrl(CustomerAPPInfo info,String fieldName) {
        Object objUrl = ReflectUtil.getFieldValue(info,fieldName);
        if (null==objUrl || StrUtil.isBlank(objUrl.toString())) {
            throw new ServiceException("该机构未配置此阿帕云服务接口");
        }
        return objUrl.toString();
    }


    /**
     * 客户app信息
     */
    @Data
    class CustomerAPPInfo{

        /** 客户code **/
        private String customerCode;
        /** app名字 **/
        private String appName;
        /** app密码 **/
        private String appSecret;
        /** 阿帕云 获取token接口地址 **/
        private String arpaCloudTokenApiUrl;
        /** 阿帕云token失效间隔 秒 **/
        private long expireSecendInterval;
        /** 阿帕云访问token **/
        private String token;
        /** 阿帕云token失效时间 **/
        private LocalDateTime expireTime;

        /** 阿帕云 发送jpus推送接口地址 **/
        private String arpaCloudPushJpushApiUrl;
        /** 阿帕云jpush货主访问token **/
        private String token_jpush_shipment;
        /** 阿帕云jpush货主token失效时间 **/
        private LocalDateTime expireTime_jpush_shipment;
        /** 阿帕云jpush司机访问token **/
        private String token_jpush_driver;
        /** 阿帕云jpush司机token失效时间 **/
        private LocalDateTime expireTime_jpush_dirver;

        /**
         * 查询客户充值记录
         */
        private String customerChargetList;
        /**
         * 查询客户账户信息
         */
        private String warehousingAccount;

        /** 阿帕云  仓储按单扣费接口**/
        private String orderDetailChargeUrl;

        /** 阿帕云  是否是充值用户**/
        private String rechargeUser;

        /** 阿帕云  是否是充值用户**/
        private String loadState;

        /** 阿帕云  账户余额**/
        private String customerAccount;



        //验签密码
        private String arpaCloudsignSecret;

        //电子面单标准模板
        private String templateList;

        //电子面单打印信息
        private String electronicFaceSheet;

        //电子面单余额
        private String electronicFaceSheetBalance;

        //取消电子面单
        private String cancelElectronicFaceSheet;


    }
}
